/**
 * 
 */

package com.chengyu.eyc.service;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Service;

import com.chengyu.eyc.constant.EycConstants;
import com.chengyu.eyc.properties.WechatProperties;
import com.chengyu.eyc.utils.RedisUtil;
import com.chengyu.eyc.utils.SpringUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
@Service
public class WechatServiceImpl implements WechatService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private WechatProperties wechatProperties;

    @SuppressWarnings("unchecked")
    @Override
    public String getAccessToken(String userId) {
        String accessToken = null;
        String accessTokenKey = EycConstants.CacheKey.getAccessTokenKey(userId);
        if (RedisUtil.exists(accessTokenKey)) {
            accessToken = RedisUtil.get(accessTokenKey).toString();
        }
        if (StrUtil.isEmpty(accessToken)) {
            String body = HttpUtil.get(String.format(EycConstants.ACCESS_TOKEN_URL, wechatProperties.getAppId(), wechatProperties.getAppSecret()));
            if (StrUtil.isNotBlank(body)) {
                Map<String, Object> map = JSONUtil.toBean(body, Map.class);
                if (map.get(EycConstants.ACCESS_TOKEN) != null) {
                    accessToken = map.get(EycConstants.ACCESS_TOKEN).toString();
                    if (StrUtil.isNotBlank(accessToken)) {
                        RedisUtil.set(accessTokenKey, accessToken, (Integer)map.get("expires_in"));
                    }
                }
            }

        }
        return accessToken;
    }
    @SuppressWarnings("unchecked")
    @Override
    public String getOfficialAccountAccessToken() {
        String accessToken = null;
            String body = HttpUtil.get(String.format(EycConstants.ACCESS_TOKEN_URL, wechatProperties.getOfficialAccount().getAppId(), wechatProperties.getOfficialAccount().getAppSecret()));
            if (StrUtil.isNotBlank(body)) {
                Map<String, Object> map = JSONUtil.toBean(body, Map.class);
                if (map.get(EycConstants.ACCESS_TOKEN) != null) {
                    accessToken = map.get(EycConstants.ACCESS_TOKEN).toString();
                }
            }
            
       
        return accessToken;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getOpenId(String code) {
        Map<String, Object> map = null;
        String url = String.format(EycConstants.JSCODE_2_SESSION_URL, wechatProperties.getAppId(), wechatProperties.getAppSecret(), code);
        String body = HttpUtil.get(url);
        if (StrUtil.isNotBlank(body)) {
            map = JSONUtil.toBean(body, Map.class);
        }
        return map;
    }
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getUserInfo(String accessToken,String openId) {
//        String accessToken=getOfficialAccountAccessToken();
        Map<String, Object> map = null;
        String url = String.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s",accessToken ,openId);
        String body = HttpUtil.get(url);
        if (StrUtil.isNotBlank(body)) {
            map = JSONUtil.toBean(body, Map.class);
        }
        return map;
    }

    /**
     * @see com.chengyu.eyc.service.WechatService#login(java.lang.String, java.lang.String)
     */
    @Override
    public boolean login(String userName, String password) {
        try {
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, password);
            token.setDetails(new WebAuthenticationDetails(request));
            Authentication authenticatedUser = SpringUtil.getBean(AuthenticationManager.class).authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
            request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> obtainVehicleLicenseInfo(Map<String, String> params) {
        Map<String, Object> map = null;
        String accessToken = getAccessToken(params.get("userId"));// 2021-06&fileNme=vehicleLicense.png
        // "https://lichetang.com/wechat/loadImgIo?fileDir=2021-06&fileNme=vehicleLicense.png"
        String imgUrl = String.format("https://lichetang.com/wechat/loadImgIo?fileDir=%s&fileNme=%s", params.get("fileDir"), params.get("fileNme"));
        log.info("图标地址：{}", imgUrl);
        String url = String.format(EycConstants.DRIVING_URL, /*params.get("imgUrl")*/imgUrl, accessToken);
        String body = HttpUtil.post(url, map);
        log.info("识别行驶证：{}", body);
        if (StrUtil.isNotBlank(body)) {
            map = JSONUtil.toBean(body, Map.class);
        }

        return map;
    }

}
